package com.atguigu.gmall.list.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.list.repository.GoodsRepository;
import com.atguigu.gmall.list.service.SearchService;
import com.atguigu.gmall.model.list.*;
import com.atguigu.gmall.model.product.BaseAttrInfo;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.model.product.BaseTrademark;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import springfox.documentation.spring.web.json.Json;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    // 服务层调用product-client
    @Autowired
    private ProductFeignClient productFeignClient;

    // 需要获取到一个操作es的客户端
    // ElasticsearchRestTemplate 底层使用的是高级客户端
    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public void upperGoods(Long skuId) {
        // 通过productFeignClient获取到数据给Goods赋值

        Goods goods = new Goods();

        CompletableFuture<SkuInfo> skuInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
            goods.setId(skuInfo.getId());
            goods.setDefaultImg(skuInfo.getSkuDefaultImg());
            goods.setPrice(skuInfo.getPrice().doubleValue());
            goods.setTitle(skuInfo.getSkuName());
            goods.setCreateTime(new Date());
            return skuInfo;
        });

        CompletableFuture<Void> categoryCompletableFuture = skuInfoCompletableFuture.thenAcceptAsync(skuInfo -> {
            BaseCategoryView categoryView = productFeignClient.getCategoryView(skuInfo.getCategory3Id());
            goods.setCategory1Id(categoryView.getCategory1Id());
            goods.setCategory2Id(categoryView.getCategory2Id());
            goods.setCategory3Id(categoryView.getCategory3Id());
            goods.setCategory1Name(categoryView.getCategory1Name());
            goods.setCategory2Name(categoryView.getCategory2Name());
            goods.setCategory3Name(categoryView.getCategory3Name());
        });

        CompletableFuture<Void> tmCompletableFuture = skuInfoCompletableFuture.thenAcceptAsync(skuInfo -> {
            BaseTrademark trademark = productFeignClient.getTrademark(skuInfo.getTmId());
            goods.setTmId(trademark.getId());
            goods.setTmName(trademark.getTmName());
            goods.setTmLogoUrl(trademark.getLogoUrl());
        });

        CompletableFuture<Void> attrCompletableFuture = CompletableFuture.runAsync(() -> {
            List<BaseAttrInfo> attrList = productFeignClient.getAttrList(skuId);
            List<SearchAttr> searchAttrs = attrList.stream().map((baseAttrInfo -> {
                SearchAttr searchAttr = new SearchAttr();
                searchAttr.setAttrId(baseAttrInfo.getId());
                searchAttr.setAttrName(baseAttrInfo.getAttrName());
                searchAttr.setAttrValue(baseAttrInfo.getAttrValueList().get(0).getValueName());
                return searchAttr;
            })).collect(Collectors.toList());
            goods.setAttrs(searchAttrs);
        });

        CompletableFuture.allOf(skuInfoCompletableFuture,
                categoryCompletableFuture,
                tmCompletableFuture,
                attrCompletableFuture).join();

//        Goods goods = new Goods();
//        // sku基本信息
//        SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
//        goods.setId(skuInfo.getId());
//        goods.setDefaultImg(skuInfo.getSkuDefaultImg());
//        goods.setPrice(skuInfo.getPrice().doubleValue());
//        goods.setTitle(skuInfo.getSkuName());
//        goods.setCreateTime(new Date());
//
//        // sku分类信息
//        BaseCategoryView categoryView = productFeignClient.getCategoryView(skuInfo.getCategory3Id());
//        goods.setCategory1Id(categoryView.getCategory1Id());
//        goods.setCategory2Id(categoryView.getCategory2Id());
//        goods.setCategory3Id(categoryView.getCategory3Id());
//        goods.setCategory1Name(categoryView.getCategory1Name());
//        goods.setCategory2Name(categoryView.getCategory2Name());
//        goods.setCategory3Name(categoryView.getCategory3Name());
//
//        // sku的品牌信息
//        BaseTrademark trademark = productFeignClient.getTrademark(skuInfo.getTmId());
//        goods.setTmId(trademark.getId());
//        goods.setTmName(trademark.getTmName());
//        goods.setTmLogoUrl(trademark.getLogoUrl());
//
//        // sku的平台属性
//        List<BaseAttrInfo> attrList = productFeignClient.getAttrList(skuId);
//        List<SearchAttr> searchAttrs = new ArrayList<>();
//        for (BaseAttrInfo baseAttrInfo : attrList) {
//            SearchAttr searchAttr = new SearchAttr();
//            searchAttr.setAttrId(baseAttrInfo.getId());
//            searchAttr.setAttrName(baseAttrInfo.getAttrName());
//            searchAttr.setAttrValue(baseAttrInfo.getAttrValueList().get(0).getValueName());
//        }
//        goods.setAttrs(searchAttrs);

        // 保存数据到es 上架
        goodsRepository.save(goods);
    }

    @Override
    public void lowerGoods(Long skuId) {
        // 删除
        goodsRepository.deleteById(skuId);
    }

    @Override
    public void incrHotScore(Long skuId) {
        // 采用ZSet
        String hotKey = "hotScore";
        // ZSet 自增
        Double score = redisTemplate.opsForZSet().incrementScore(hotKey, "skuId:" + skuId, 1);
        // 判断
        if (score % 10 == 0) {
            // 更新es
            Optional<Goods> optionalGoods = goodsRepository.findById(skuId);
            Goods goods = optionalGoods.get();
            goods.setHotScore(score.longValue());
            goodsRepository.save(goods);
        }
    }


    @Override
    public SearchResponseVo search(SearchParam searchParam) throws IOException {
         /*
            1. 先生成对应的dsl语句
            2. 执行dsl语句
            3. 将执行的结果集封装到SearchResponseVo对象中
         */
        //先生成对应的dsl语句
        SearchRequest searchRequest = this.buildQueryDsl(searchParam);
//        执行dsl语句
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

//        将执行的结果集封装到SearchResponseVo对象中
        SearchResponseVo responseVO = this.parseSearchResult(searchResponse);
        responseVO.setPageNo(searchParam.getPageNo());
        responseVO.setPageSize(searchParam.getPageSize());
        long totalPages = (responseVO.getTotal()+searchParam.getPageSize()-1)/searchParam.getPageSize();
        responseVO.setTotalPages(totalPages);
        return responseVO;
    }



    //将执行的结果集封装到SearchResponseVo对象中,返回结果集
    private SearchResponseVo parseSearchResult(SearchResponse searchResponse) {
        //  trademarkList,attrsList,goodsList,total 这四个属性在这个方法中 parseSearchResult  赋值！
        SearchResponseVo searchResponseVo = new SearchResponseVo();
        //  获取到最外层的hits
        SearchHits hits = searchResponse.getHits();

        SearchHit[] hits1 = hits.getHits();
        //goodsList
        List<Goods> goodsArrayList = new ArrayList<>();
        for (SearchHit documentFields : hits1) {
            String sourceAsString = documentFields.getSourceAsString();
            Goods goods = JSON.parseObject(sourceAsString,Goods.class);

            if (documentFields.getHighlightFields().get("title")!=null){
                Text title =   documentFields.getHighlightFields().get("title").getFragments()[0];
                goods.setTitle(title.toString());
            }

            goodsArrayList.add(goods);
        }
        searchResponseVo.setGoodsList(goodsArrayList);
        //trademarkList 品牌 聚合中获取
        Map<String, Aggregation> aggregationMap = searchResponse.getAggregations().asMap();
        ParsedLongTerms tmIdAgg = (ParsedLongTerms) aggregationMap.get("tmIdAgg");
        List<SearchResponseTmVo> trademarkList = tmIdAgg.getBuckets().stream().map((bucket) -> {
            SearchResponseTmVo searchResponseTmVo = new SearchResponseTmVo();

            searchResponseTmVo.setTmId((Long) bucket.getKeyAsNumber());

            //tmNameAgg
            ParsedStringTerms tmNameAgg = bucket.getAggregations().get("tmNameAgg");
            String keyAsString = tmNameAgg.getBuckets().get(0).getKeyAsString();
            searchResponseTmVo.setTmName(keyAsString);

            //tmLogoUrlAgg
            ParsedStringTerms tmLogoUrlAgg = bucket.getAggregations().get("tmLogoUrlAgg");
            String asString = tmLogoUrlAgg.getBuckets().get(0).getKeyAsString();
            searchResponseTmVo.setTmLogoUrl(asString);
            return searchResponseTmVo;
        }).collect(Collectors.toList());

        searchResponseVo.setTrademarkList(trademarkList);
        //attrsList
        ParsedNested attrAgg = (ParsedNested) aggregationMap.get("attrAgg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attrIdAgg");
        List<SearchResponseAttrVo> attrsList = attrIdAgg.getBuckets().stream().map((bucket) -> {
            SearchResponseAttrVo searchResponseAttrVo = new SearchResponseAttrVo();
            //  给AttrId 赋值
            searchResponseAttrVo.setAttrId((Long) bucket.getKeyAsNumber());
            //attrNameAgg
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attrNameAgg");
            String keyAsString = attrNameAgg.getBuckets().get(0).getKeyAsString();
            searchResponseAttrVo.setAttrName(keyAsString);
            //attrValueAgg
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attrValueAgg");
            List<String> list = attrValueAgg.getBuckets().stream().map(Terms.Bucket::getKeyAsString).collect(Collectors.toList());
//            List<String> collect = attrValueAgg.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            searchResponseAttrVo.setAttrValueList(list);
            return searchResponseAttrVo;
        }).collect(Collectors.toList());
        searchResponseVo.setAttrsList(attrsList);

        //获取到总条数
        searchResponseVo.setTotal(hits.getTotalHits().value);
        return searchResponseVo;
    }

    /**
     * 先生成对应的dsl语句
     * @param searchParam
     * @return
     */
    private SearchRequest buildQueryDsl(SearchParam searchParam) {
        //searchSourceBuilder-->相当于dsl语句中的大括号
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //  判断 用户是否根据分类Id 检索！
        if (!StringUtils.isEmpty(searchParam.getCategory1Id())){
            //  创建一个filter ---> term {"category1Id": "2"}
            boolQueryBuilder.filter(QueryBuilders.termQuery("category1Id",searchParam.getCategory1Id()));
        }
        if (!StringUtils.isEmpty(searchParam.getCategory2Id())){
            //  创建一个filter ---> term {"category2Id": "13"}
            boolQueryBuilder.filter(QueryBuilders.termQuery("category2Id",searchParam.getCategory2Id()));
        }
        if (!StringUtils.isEmpty(searchParam.getCategory3Id())){
            //  创建一个filter ---> term {"category3Id": "61"}
            boolQueryBuilder.filter(QueryBuilders.termQuery("category3Id",searchParam.getCategory3Id()));
        }
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("title",searchParam.getKeyword()).operator(Operator.AND));
        }
        //  获取到品牌数据： trademark=2:华为
        String trademark = searchParam.getTrademark();
        if (!StringUtils.isEmpty(trademark)){
            //截断
            String[] split = trademark.split(":");
            if (split!=null&&split.length==2){
                boolQueryBuilder.filter(QueryBuilders.termQuery("tmId",split[0]));
            }
        }

        //  通过平台属性值进行过滤！ props=23:4G:运行内存&props=24:128G:机身内存
        String[] props = searchParam.getProps();
        if(!StringUtils.isEmpty(props)){
            for (String prop : props) {
                String[] split = prop.split(":");
                if (split!=null&&split.length==3){
                    //  声明两个bool 对象
                    BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
                    BoolQueryBuilder subQueryBuilder = QueryBuilders.boolQuery();
                    subQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId",split[0]));
                    subQueryBuilder.must(QueryBuilders.termQuery("attrs.attrValue",split[1]));
                    //ScoreMode-->评分模式
                    queryBuilder.must(QueryBuilders.nestedQuery("attrs",subQueryBuilder, ScoreMode.None));

                    //  将封装平台属性Id 平台属性值名称查询 赋值给 外层的 bool
                    boolQueryBuilder.filter(queryBuilder);
                }
            }
        }

        //  { query ---> bool }
        searchSourceBuilder.query(boolQueryBuilder);//-->相当于dsl语句中query中嵌套的bool语句

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style=color:red>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        //分页
        int from = (searchParam.getPageNo()-1)*searchParam.getPageSize();
        searchSourceBuilder.from(from);
        //  有个默认值每页显示的大小
        searchSourceBuilder.size(searchParam.getPageSize());

        //  设置排序： 1:hotScore 热度 2:price 价格
        //  前端传递的参数：order=1:desc  | order=1:asc  order=2:desc  | order=2:asc
        String order = searchParam.getOrder();
        if (!StringUtils.isEmpty(order)){
            String[] split = order.split(":");
            if (split!=null&&split.length==2){
                String field = "";
                switch (split[0]){
                    case "1":
                        field = "hotScore";
                        break;
                    case "2":
                        field = "price";
                        break;
                }
                searchSourceBuilder.sort(field,"asc".equals(split[1])? SortOrder.ASC:SortOrder.DESC);
            }else {
                //  默认排序规则！
                searchSourceBuilder.sort("hotScore",SortOrder.DESC);
            }
        }

        //  聚合：平台属性：nested
        searchSourceBuilder.aggregation(AggregationBuilders.nested("attrAgg","attrs")
            .subAggregation(AggregationBuilders.terms("attrIdAgg").field("attrs.attrId")
            .subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName"))
                    .subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue")))
        );
        //  聚合：品牌
        searchSourceBuilder.aggregation(AggregationBuilders.terms("tmIdAgg").field("tmId")
            .subAggregation(AggregationBuilders.terms("tmNameAgg").field("tmName"))
                .subAggregation(AggregationBuilders.terms("tmLogoUrlAgg").field("tmLogoUrl"))

        );

        //  其他的设置！ 查询到那些字段显示
        searchSourceBuilder.fetchSource(new String[]{"id","defaultImg","title","price"},null);

        SearchRequest searchRequest = new SearchRequest("goods");

        String dsl = searchSourceBuilder.toString();
        System.out.println("dsl:\t"+dsl);
        searchRequest.source(searchSourceBuilder);
        return searchRequest;

        //        官网给的案例： 通过案例可以看到所有的dsl 语句都在此生成！
        //        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        //        searchRequest.source(searchSourceBuilder);
    }
}
